// pages/login/index.js
const app = getApp();
const api = require('../../../utils/api').apis;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sourceType:'regist',
    openId: '',
    userId: '',
    visibleNote: Number,
    nei: '',
    Numis: true,
    datiis: false,
    showLoginPage: false,
    userInfo: null,
    hasUserInfo: false,
    canIUse: '',
    type: '',
    orderId: '',
    session_key: '',
    loginType: 'wechat',
    listdata: {},
    id: '',
    code: '',
    appletOpenId: '',
    buttonis: true,
    navurl: '',
    couresid: '',
    name: '',
    list2: [{
      id: 0,
      name: '求职就业',
      active: 0
    }, {
      id: 1,
      name: '技能提升',
      active: 0
    }, {
      id: 2,
      name: '工资翻倍',
      active: 0
    }],
    Url: '',
    Router: ''
  },
  bindcheck() {

    if (this.data.id == '' || this.data.id == undefined || this.data.id == null) {
      wx.showToast({
        title: '请您先选择就业方向',
        icon: 'none'
      })
    } else if (this.data.nei == '') {
      wx.showToast({
        title: '请您先选择学习目的',
        icon: 'none'
      })
    } else {
      api.getOpenCourse({
        industryId: this.data.id
      }).then(res => {
        console.log(res.data)
      }).catch(err => {
        // console.log(err)
      })
      api.addUserRecord({
        incomeAmount: '暂无',
        professionalLevel: '暂无',
        employmentDirection: this.data.name,
        industryId: this.data.id,
        learnPurpose: this.data.nei,
      }).then(res => {
        if (this.data.Url || this.data.Router) {
          console.log('76 含有Router', this.data.Url)
          if (this.data.Router == '/pages/index/index' ||this.data.Router == '/pages/learn/index' || this.data.Router == '/pages/mine/index' || this.data.Router == '/pages/curriculum/index') {
            wx.switchTab({
              url: this.data.Router,
            })
            wx.removeStorageSync('Router')
            wx.removeStorageSync('Url')
          } else {
            console.log('84 跳转砍价', this.data.Url)
            wx.navigateTo({
              url: this.data.Url,
            })
            wx.removeStorageSync('Router')
            wx.removeStorageSync('Url')
          }
        } else {
          console.log('92 没有获取到 ')
          if (this.data.couresid == null) {
            wx.switchTab({
              url: this.data.navurl
            })
          } else {
            wx.navigateTo({
              url: this.data.navurl,
            })
          }
        }

      })
    }
  },
  // 获取code
  // 获取code
  getSession() {
    var user = wx.getStorageSync('userInfo')
    // console.log()
    // if (user) {
    wx.login({
      success: res => {
        if (res.code) {
          wx.showLoading({
            title: '加载中',
          })
          console.log(res)
          var code = res.code
          api.getLogin({
            code: code
          }).then(res => {
            // wx.setStorageSync('openId', res.data.userBO.appletOpenId)
            var token = res.data.token
            wx.setStorageSync('Xd_Token', token)
            api.getuserInfo({
              token: token
            }).then(res => {
              wx.setStorageSync('userInfo', res.data)
              console.log(res)
            })

            // 判断之前是否授权登录过获取手机号
            if (res.code != '00002') {
              wx.hideLoading()
              console.log(res.data)
              var userNumber = res.data.userBO.phone
              wx.setStorageSync('userNumber', userNumber)

              this.setData({
                Numis: false,
                datiis: true,
              })
              //判断是否从指定页面登录
              if (this.data.Url || this.data.Router) {
                console.log('147 含有Router')
                if (this.data.Router == '/pages/index/index' || this.data.Router == '/pages/learn/index' || this.data.Router == '/pages/mine/index' || this.data.Router == '/pages/curriculum/index') {
                  wx.switchTab({
                    url: this.data.Router,
                  })
                  wx.removeStorageSync('Router')
                  wx.removeStorageSync('Url')
                } else {
                  console.log('155 跳转砍价', this.data.Url)
                  wx.navigateTo({
                    url: this.data.Url,
                  })
                  wx.removeStorageSync('Router')
                  wx.removeStorageSync('Url')
                }
              } else {
                console.log('163 没有获取到')
                if (this.data.couresid == null) {
                  wx.switchTab({
                    url: '../../../pages/index/index'
                  })
                } else {
                  wx.navigateTo({
                    url: this.data.navurl
                  })
                }
              }
            } else {

              this.setData({
                openId: res.data.openid
              })
              wx.setStorageSync('openId', res.data.openid)
              console.log(res.data.openid)
              wx.hideLoading()
              this.setData({
                openId: res.data.openid,
                session_key: res.data.session_key
              })
            }
          })
        }
      }
    })
  },
  // getUserProfile(e) {
  //   // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
  //   // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
  //   wx.getUserProfile({
  //     desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
  //     success: (res) => {
  //       this.setData({
  //         userInfo: res.userInfo,
  //         hasUserInfo: true
  //       })
  //     }
  //   })
  // },
  // 获取用户信息
  getUserProfile(e) { //授权个人信息
    console.log(wx.getUserProfile)
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        console.log(res)
        wx.setStorageSync('openId', this.data.openId)
        if (this.data.userInfo) {
          this.setData({
            visibleNote: 2 // 存入的状态
          });
        }
        let info = wx.getStorageSync('userInfo')
        if (this.data.userInfo) {
          console.log('已授权')
          this.setData({
            buttonis: false
          })
          this.getSession()
        } else {
          console.log('未授权')
        }

      }
    })
    
  },
  //获取手机号
  getPhoneNumber(e) {
    if (e.detail.errMsg == "getPhoneNumber:fail user deny") { // 拒绝获取手机号码授权
      wx.showModal({
        title: '警告',
        content: '获取手机号失败 !',
        showCancel: false,
        confirmText: '关闭',
        success: function (res) {
          if (res.confirm) {}
        }
      });
      wx.navigateTo({
        url: '/login/pages/login-3/index',
      })
      this.setData({
        buttonis: true
      })
    } else if (e.detail.errMsg == "getPhoneNumber:ok") {
      var _this = this
      var encryptedData = e.detail.encryptedData;
      //跳转至首页
      api.getberdecode({
        iv: e.detail.iv,
        encryptedData: e.detail.encryptedData,
        sessionKey: this.data.session_key
      }).then(res => {
        if (res.code == '00004') {
          wx.switchTab({
            url: this.data.navurl
          })
        } else {
          console.log(res)
          var userNumber = res.data.phoneNumber
          wx.setStorageSync('userNumber', userNumber)
          console.log(_this.data.openId)
          // 登录串参换取token
          api.binding({
            checkResult: 'yes',
            phone: userNumber,
            // 小程序id
            appletOpenId: _this.data.openId,
            // 用户来源类型，好友邀请，自己注册
            sourceType: _this.data.sourceType,
            sourceChannel:"program",
            // sourceId:_this.data.userId
            // 微信的名字头像
            username: _this.data.userInfo.nickName,
            userImgSrc: _this.data.userInfo.avatarUrl,
          }).then(res => {
            console.log(res)
            if (res.success) {
              if (res.data.isAnswer == false) {
                console.log('未答题')
                _this.setData({
                  Numis: false,
                  datiis: true
                })
              } else {
                console.log('已答题')
                //判断是否从指定页面登录
                if (this.data.Url || this.data.Router) {
                  console.log('282 含有Router')
                  if (this.data.Router == '/pages/index/index' || this.data.Router == '/pages/learn/index' || this.data.Router == '/pages/mine/index' || this.data.Router == '/pages/curriculum/index') {
                    wx.switchTab({
                      url: this.data.Router,
                    })
                    wx.removeStorageSync('Router')
                    wx.removeStorageSync('Url')
                  } else {
                    console.log('291 跳转砍价',this.data.Url)
                    wx.navigateTo({
                      url: this.data.Url,
                    })
                    wx.removeStorageSync('Router')
                    wx.removeStorageSync('Url')
                  }
                } else {
                  console.log('298 没有获取到')
                  if (this.data.couresid == null) {
                    wx.switchTab({
                      url: this.data.navurl
                    })
                  } else {
                    wx.navigateTo({
                      url: this.data.navurl,
                    })
                  }
                }
              }
              var token = res.data.token
              wx.setStorageSync('Xd_Token', token)
              api.getuserInfo({
                token: token
              }).then(res => {
                wx.setStorageSync('userInfo', res.data)

                console.log(res.data)
              })

            }
          })
        }
      })
    }
  },

  // 就业方向的选中
  activeChange: function (e) {
    var id = e.currentTarget.dataset.id
    var name = e.currentTarget.dataset.name;
    var list = e.currentTarget.dataset.ind;
    var arr = this.data.listdata;
    this.setData({
      id: id,
      list: list
    })
    arr.map(item => {
      if (id == item.id) {

        item.active = 1
        this.setData({
          name: name,
          id: item.id
        })
      } else {
        item.active = 0
      }
    })
    this.setData({
      listdata: arr
    })
  },
  activeChange2: function (e) {
    var ind = e.currentTarget.dataset.ind;
    var nei = e.currentTarget.dataset.nei;
    var arr = this.data.list2;
    arr.map(item => {
      if (ind == item.id) {
        item.active = 1
        this.setData({
          nei: nei
        })
      } else {
        item.active = 0
      }
    })
    this.setData({
      list2: arr
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    this.getSession()
    var couresid = options.id ? options.id : null
    var classification = options.classification ? options.classification : null
    var Url = wx.getStorageSync('Url');
    var Router = wx.getStorageSync('Router');
    if(options.userActivityId){
      this.setData({
        sourceType:'friend'
      })
    } else{
      this.setData({
        sourceType:'regist'
      })
    }
    console.log(383, 'url', Url, Router)
    this.setData({
      Url,
      Router
    })
    if (couresid == null) {
      console.log('登录')
      this.setData({
        navurl: '../../../pages/index/index',
        couresid: couresid,
      })
    } else {
      console.log('未登录')
      this.setData({
        couresid: couresid,
        navurl: '/curriculum/pages/course/index?id=' + couresid
      })
    }

    // 课程 获取行业下拉框数据
    api.busIness({

    }).then(res => {
      wx.showLoading({
        title: '加载中',
      })
      var arr = res.data
      arr.map(item => {
        item.active = 0
      })
      this.setData({
        listdata: arr
      })
      wx.hideLoading()
      // console.log(res.data)
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var token = wx.getStorageSync('Xd_Token')
    if (token) {
      console.log('已经登陆过')
      wx.switchTab({
        url: '../../../pages/index/index',
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})